package com.example.lib_common.websocket

import android.os.Handler
import android.util.Log
import com.alibaba.android.arouter.utils.TextUtils
import com.example.lib_common.utils.LoggerUtils
import org.java_websocket.handshake.ServerHandshake
import java.lang.Exception
import java.net.URI

/**
 * @author yaotianxue
 * @description
 * @date 2025/3/4
 */
class WebSocketUtils {
    private var websocket_url:String = "10.161..........."
    private var receiverMsgListener:ReceiverMsgListener? = null
    private var wsClient:IVideoWebSocketClient? = null //客户端

    /**
     * 心跳逻辑
     */
    companion object{
        const val HEART_BEAT_TIME = 1000 * 10L //每隔10秒发一次心跳包
    }
    private val handler = Handler()
    private val runnable = object :Runnable{
        override fun run() {
            if (wsClient == null){
                initWebSocketClient()
            }else{
                if (wsClient?.isOpen == true){  //如果链接已经打开，则发送心跳包
                    wsClient?.send("heartbeat")
                    LoggerUtils.d("websocket","发送心跳包")
                }else{
                    reconnectWs() //重连
                }
            }
            //每隔一定时间重新发送心跳包
            handler.postDelayed(this,HEART_BEAT_TIME)
        }

    }


    constructor(builder: Builder){
        if (!TextUtils.isEmpty(builder.websocket_url)){
            this.websocket_url = builder.websocket_url
        }
        this.receiverMsgListener = builder.receiverMsgListener
        initWS()
    }

    /**
     * 初始化websocket
     */
    fun initWS(){
        handler.postDelayed(runnable,HEART_BEAT_TIME) //开启心跳检测
        if (wsClient == null){
            //创建客户端并建立链接
            initWebSocketClient()
        }else if (wsClient?.isClosed == true){
            //重新建立链接
            reconnectWs()
        }
    }

    /**
     * 创建客户端并建立链接
     */
    fun initWebSocketClient(){
        val uri = URI.create("ws://$websocket_url")
        wsClient = object :IVideoWebSocketClient(uri){
            override fun onClose(code: Int, reason: String?, remote: Boolean) {
                super.onClose(code, reason, remote)
                receiverMsgListener?.onClose(code,reason,remote)
            }
            override fun onOpen(handshakedata: ServerHandshake?) {
                super.onOpen(handshakedata)
                receiverMsgListener?.onOpen(handshakedata)
            }
            override fun onMessage(message: String?) {
                super.onMessage(message)
                receiverMsgListener?.onMessage(message)
            }
            override fun onError(ex: Exception?) {
                super.onError(ex)
                receiverMsgListener?.onError(ex)
            }
        }
        //设置链接超时
        wsClient?.connectionLostTimeout = 110*1000
        //建立链接
        wsClient?.connect()
    }

    /**
     * 重新建立链接
     */
    fun reconnectWs(){
        handler.removeCallbacks(runnable)
        wsClient?.reconnect()
    }

    /**
     * 断开链接
     */
    fun disconnectWs(){
        wsClient?.close()
        wsClient = null
        handler.removeCallbacks(runnable) //移除心跳检测
    }













    //构建者
    class Builder{
         var websocket_url:String = ""
         var receiverMsgListener:ReceiverMsgListener? = null

        fun setWebsocketUrl(url:String):Builder{
            this.websocket_url = url
            return this
        }
        fun setReceiverMsgListener(receiverMsgListener: ReceiverMsgListener):Builder{
            this.receiverMsgListener = receiverMsgListener
            return this
        }
        fun build():WebSocketUtils{
            return WebSocketUtils(this)
        }
    }

}